<?php
/**
 * 微信oAuth认证示例
 */

include_once MODPATH.'/passport/classes/passport/weixin/wechat.class.php';

class Passport_Wechat
{
    private $_options;
    private $_wechat;

    public function __construct ($options)
    {
        $this->_otpions = $options;
        $this->_wechat  = new WeChat($this->_otpions);
    }

    public function getUserInfo ()
    {
        // 获取Code
        $code = isset($_GET['code']) ? $_GET['code'] : '';
        if (empty($code))
        {
            $this->redirectForCode();
            return;
        }

        // 获取网页授权Token
        $json = $this->_wechat->getOauthAccessToken($code);
        if (empty($json))
            throw new Exception("无法获取用户信息Token");

        $openId      = isset($json['openid']) ? $json['openid'] : '';
        $accessToken = isset($json['access_token']) ? $json['access_token'] : '';

        $userInfo    = $this->_wechat->getOauthUserinfo($accessToken, $openId);
        if (empty($userInfo))
            throw new Exception("无法获取用户信息Info");
            
        return $userInfo;
    }

    private function redirectForCode ()
    {
        $urlCallback = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $url   = $this->_wechat->getOauthRedirect($urlCallback);
        header("Location: $url");
        exit;
    }
}


